package com.team.childapp.util;


import com.team.childapp.base.App;
import com.team.childapp.bean.ai.GenerateBean;
import com.team.childapp.config.BaseConfig;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.internal.sse.RealEventSource;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;

public class AIHelpUtil {
    private static AIHelpUtil single;
    private OkHttpClient okHttpClient;
    private static final String requestURL = "https://sit-gw.ai-tongban.com/appbc/chat/generate";
    private static final long DEFAULT_MILLISECONDS = 5000;//默认的超时时间30S


    private AIHelpUtil() {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(DEFAULT_MILLISECONDS, TimeUnit.SECONDS)   // 建立连接的超时时间
                .readTimeout(DEFAULT_MILLISECONDS, TimeUnit.MINUTES)  // 建立连接后读取数据的超时时间
                .build();
    }

    public static AIHelpUtil getInstance() {
        if (single == null) {
            synchronized (AIHelpUtil.class) {
                if (single == null) {
                    single = new AIHelpUtil();
                }
            }
        }
        return single;
    }

    /**
     * 请求文生文
     *
     * @param prompt
     * @param callBack
     */
    public void requestText2Text(String prompt, Text2TextCallBack callBack) {
        String token = App.Companion.application().getShareData().getString(BaseConfig.getTOKEN_ID(),"") ;
        Map<String, Object> map = new HashMap<>();
        map.put("prompt", prompt);
        map.put("fileUrl", "");
        map.put("stream", true);
        map.put("type", 1);
        map.put("modeType", 1);
        map.put("chatType", AIDefine.CHAT_TYPE_TEXT2TEXT);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json"), JsonSerializer.serialize(map));
        Request request = new Request.Builder()
                .url(requestURL)
                .addHeader("Authorization","Bearer " + token)
                .post(body) // 设置请求方式为POST，并设置请求体
                .build();
        RealEventSource realEventSource = new RealEventSource(request, new EventSourceListener() {
            @Override
            public void onEvent(EventSource eventSource, String id, String type, String data) {
                GenerateBean bean = JsonSerializer.deSerialize(data, GenerateBean.class);
                if (callBack != null && bean != null) {
                    callBack.onDataBack(bean);
                }
                LogUtils.showLog("Text2Text", bean.getContent());
            }
        });
        realEventSource.connect(okHttpClient);
    }

    /**
     * 请求文生图
     *
     * @param prompt
     * @param callBack
     */
    public void requestText2Image(String prompt, Text2TextCallBack callBack) {
        String token = App.Companion.application().getShareData().getString(BaseConfig.getTOKEN_ID(),"") ;
        Map<String, Object> map = new HashMap<>();
        map.put("prompt", prompt);
        map.put("fileUrl", "");
        map.put("stream", true);
        map.put("chatType", AIDefine.CHAT_TYPE_TEXT2IMAGE);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json"), JsonSerializer.serialize(map));
        Request request = new Request.Builder()
                .url(requestURL)
                .addHeader("Authorization","Bearer " + token)
                .post(body) // 设置请求方式为POST，并设置请求体
                .build();
        RealEventSource realEventSource = new RealEventSource(request, new EventSourceListener() {
            @Override
            public void onEvent(EventSource eventSource, String id, String type, String data) {
                GenerateBean bean = JsonSerializer.deSerialize(data, GenerateBean.class);
                if (callBack != null && bean != null) {
                    callBack.onDataBack(bean);
                }
                LogUtils.showLog("Text2Image", bean.toString());
            }
        });
        realEventSource.connect(okHttpClient);
    }

    /**
     * 请求图生图
     ** @param callBack
     */
    public void requestImage2Image(String prompt,File file, Text2TextCallBack callBack) {
        String token = App.Companion.application().getShareData().getString(BaseConfig.getTOKEN_ID(),"") ;
        String base64 = FileHelper.encodeFileToBase64(file);
        LogUtils.showLog("zhu","options = " + file.length());
        Map<String, Object> map = new HashMap<>();
        map.put("prompt", prompt);
        map.put("fileBase64", base64);
        map.put("stream", true);
        map.put("chatType", AIDefine.CHAT_TYPE_IMAGE2IMAGE);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json"), JsonSerializer.serialize(map));
        Request request = new Request.Builder()
                .url(requestURL)
                .addHeader("Authorization","Bearer " + token)
                .post(body) // 设置请求方式为POST，并设置请求体
                .build();
        RealEventSource realEventSource = new RealEventSource(request, new EventSourceListener() {
            @Override
            public void onEvent(EventSource eventSource, String id, String type, String data) {
                GenerateBean bean = JsonSerializer.deSerialize(data, GenerateBean.class);
                if (callBack != null && bean != null) {
                    callBack.onDataBack(bean);
                }
                LogUtils.showLog("Image2Image", bean.toString());
            }
        });
        realEventSource.connect(okHttpClient);
    }

    /**
     * 请求AI相机
     *
     * @param prompt
     * @param callBack
     */
    public void requestAICamera(String prompt,File file, Text2TextCallBack callBack) {
        String token = App.Companion.application().getShareData().getString(BaseConfig.getTOKEN_ID(),"") ;
        String base64 = FileHelper.encodeFileToBase64(file);
        Map<String, Object> map = new HashMap<>();
//        map.put("prompt", prompt);
        map.put("portraitStyle", prompt);
        map.put("fileBase64", base64);
        map.put("stream", true);
        map.put("chatType", AIDefine.CHAT_TYPE_PORTRAIT_STYLE_TRANSFER);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json"), JsonSerializer.serialize(map));
        Request request = new Request.Builder()
                .url(requestURL)
                .addHeader("Authorization","Bearer " + token)
                .post(body) // 设置请求方式为POST，并设置请求体
                .build();
        RealEventSource realEventSource = new RealEventSource(request, new EventSourceListener() {
            @Override
            public void onEvent(EventSource eventSource, String id, String type, String data) {
                GenerateBean bean = JsonSerializer.deSerialize(data, GenerateBean.class);
                if (callBack != null && bean != null) {
                    callBack.onDataBack(bean);
                }
                LogUtils.showLog("Image2Image", bean.toString());
            }
        });
        realEventSource.connect(okHttpClient);
    }

    /**
     * 图片解释
     * @param prompt
     * @param file
     * @param callBack
     */
    public void requestImage2Text(String prompt,File file, Text2TextCallBack callBack) {
        String token = App.Companion.application().getShareData().getString(BaseConfig.getTOKEN_ID(),"") ;
        String base64 = FileHelper.encodeFileToBase64(file);
        Map<String, Object> map = new HashMap<>();
        map.put("prompt", prompt);
        map.put("fileBase64", base64);
        map.put("stream", true);
        map.put("chatType", AIDefine.CHAT_TYPE_IMAGE2TEXT);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json"), JsonSerializer.serialize(map));
        Request request = new Request.Builder()
                .url(requestURL)
                .addHeader("Authorization","Bearer " + token)
                .post(body) // 设置请求方式为POST，并设置请求体
                .build();
        RealEventSource realEventSource = new RealEventSource(request, new EventSourceListener() {
            @Override
            public void onEvent(EventSource eventSource, String id, String type, String data) {
                GenerateBean bean = JsonSerializer.deSerialize(data, GenerateBean.class);
                if (callBack != null && bean != null) {
                    callBack.onDataBack(bean);
                }
                LogUtils.showLog("Image2Text", bean.toString());
            }
        });
        realEventSource.connect(okHttpClient);
    }

    public interface Text2TextCallBack {
        void onDataBack(GenerateBean generateBean);
    }

    public interface AIDefine {
        String CHAT_TYPE_TEXT2TEXT = "TEXT_2_TEXT";//文生文
        String CHAT_TYPE_TEXT2IMAGE = "TEXT_2_IMAGE";//文生图
        String CHAT_TYPE_IMAGE2IMAGE = "IMAGE_2_IMAGE";//图生图
//        String CHAT_TYPE_IMAGE2TEXT = "GOSR";//图片解释
        String CHAT_TYPE_IMAGE2TEXT = "IMAGE_2_TEXT";//原图片解释
        String CHAT_TYPE_PORTRAIT_STYLE_TRANSFER= "PORTRAIT_STYLE_TRANSFER";//AI相机

        //卡通、梦幻、漫画、像素、科幻
        String CAMERA_KA_TONG = "卡通";
        String CAMERA_MENG_HUAN = "梦幻";
        String CAMERA_MAN_HUA = "漫画";
        String CAMERA_XIANG_SU = "像素";
        String CAMERA_KE_HUAN = "科幻";
    }
}
